import 'package:aichat_flutter_wallet/module/module_dapp/widgets/hover_status.dart';
import 'package:aichat_flutter_wallet/module/module_dapp/provider/dapp_provider.dart';
import 'package:aichat_flutter_wallet/module/module_browser/viewmodel/before_browser.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:lib_database/src/bean.dart';
import 'package:lib_util/common/extentions.dart';
import 'package:provider/provider.dart';
import '../../../module_common/widgets/image/public_image.dart';
import '../../../module_common/widgets/public_tip/public_tip.dart';
import 'package:lib_database/sp.dart';

class DAppFavoriteUtil {
  static showSetFavorite(
    BuildContext context, {
    String title = '',
    required DAppBean DApp,
    Function? onConfirm = null,
    Function? onClose = null,
    bool? needToast = false,
  }) {
    try {
      bool isFavorite = Provider.of<DAppProvider>(context, listen: false)
          .isFavoriteDAppExisted(DApp);

      // 不需要弹窗
      if (isFavorite) {
        Provider.of<DAppProvider>(context, listen: false).removeFavorite(DApp);
      } else {
        Provider.of<DAppProvider>(context, listen: false).addFavorite(DApp);
        // if (needToast!)
        //   Toast.show(context,
        //       message: 'Favorites succeeded',
        //       duration: Duration(milliseconds: 2000));
      }
      onConfirm?.call(!isFavorite);
      return;
      List<String> list;
      if (isFavorite)
        list = SP().getCancelStatusList();
      else
        list = SP().getFavoriteStatusList();

      // 是否需要弹窗
      bool status = list.contains(DApp.uid!);
      print('status-${status}');

      if (status) {
        if (isFavorite) {
          Provider.of<DAppProvider>(context, listen: false)
              .removeFavorite(DApp);
        } else {
          Provider.of<DAppProvider>(context, listen: false).addFavorite(DApp);
          if (needToast!) {
            Toast.show(context,
                message: 'Favorites succeeded',
                duration: Duration(milliseconds: 2000));
          }
        }
        onConfirm?.call();
      } else {
        return showModalBottomSheet(
            context: context,
            backgroundColor: Colors.transparent,
            isScrollControlled: true,
            builder: (_) {
              return FavoritePup(
                  DApp: DApp,
                  title: title,
                  onConfirm: onConfirm,
                  needToast: needToast,
                  onClose: onClose);
            });
      }
      // List<String> list;
      // if (isFavorite)
      //   list = SP().getCancelStatusList();
      // else
      //   list = SP().getFavoriteStatusList();

      // // 是否需要弹窗
      // bool status = list.contains(DApp.uid!);
      // print('status-${status}');

      // if (status) {
      //   if (isFavorite) {
      //     Provider.of<DAppProvider>(context, listen: false).removeFavorite(DApp);
      //   } else {
      //     Provider.of<DAppProvider>(context, listen: false).addFavorite(DApp);
      //     Toast.show(context, message: 'Favorites succeeded', duration: Duration(milliseconds: 2000));
      //   }
      //   onConfirm?.call();
      // } else {
      //   return showModalBottomSheet(
      //       context: context,
      //       backgroundColor: Colors.transparent,
      //       isScrollControlled: true,
      //       builder: (_) {
      //         return FavoritePup(DApp: DApp, title: title, onConfirm: onConfirm, onClose: onClose);
      //       });
      // }
    } catch (err) {
      print(err);
    }
  }
}

class FavoritePup extends StatefulWidget {
  FavoritePup(
      {super.key,
      required this.DApp,
      this.title,
      this.onConfirm,
      this.onClose,
      this.needToast});
  final DAppBean DApp;
  final String? title;
  final bool? needToast;
  Function? onConfirm;
  Function? onClose;
  @override
  State<FavoritePup> createState() => _FavoritePup();
}

class _FavoritePup extends State<FavoritePup> {
  bool isCheck = false;

  @override
  Widget build(BuildContext context) {
    bool isFavorite = Provider.of<DAppProvider>(context, listen: false)
        .isFavoriteDAppExisted(widget.DApp);
    print('isFavorite-${isFavorite}');
    return IntrinsicHeight(
        child: Container(
      padding: EdgeInsets.fromLTRB(20, 0, 20, 44),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.only(
            topLeft: Radius.circular(20), topRight: Radius.circular(20)),
      ),
      child: Column(children: [
        Container(
          width: double.infinity,
          height: 50.w,
          child: Stack(alignment: Alignment.center, children: [
            Positioned(
              left: 0,
              top: 15,
              child: GestureDetector(
                onTap: () {
                  widget.onClose?.call();
                  Navigator.pop(context);
                },
                child: Image.asset(
                  'assets/images/dapp/close.png',
                  height: 20.w,
                  width: 20.w,
                  //设置图片在左边对齐
                  alignment: Alignment.centerLeft,
                ),
              ),
            ),
            Text(!isFavorite ? 'Favorites Dapp' : 'Cancel Favorites',
                textAlign: TextAlign.center,
                style: TextStyle(
                    fontSize: 16.sp,
                    fontWeight: FontWeight.w500,
                    color: Color.fromRGBO(51, 51, 51, 1))),
          ]),
        ),
        if (isFavorite)
          Container(
            width: 335.w,
            margin: EdgeInsets.fromLTRB(0, 10, 0, 10),
            child: RichText(
              softWrap: true,
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
              text: TextSpan(
                text: 'Confirm to cancel',
                style: TextStyle(
                    color: Color.fromRGBO(134, 131, 145, 1),
                    fontSize: 14.0.sp,
                    fontWeight: FontWeight.w400),
                children: [
                  TextSpan(
                    text: ' "${widget.DApp.name!}" ',
                    style: TextStyle(
                        color: Color.fromRGBO(51, 51, 51, 1),
                        fontSize: 14.0.sp,
                        fontWeight: FontWeight.w400),
                  ),
                  TextSpan(
                      text: 'in Favorites?',
                      style: TextStyle(
                          color: Color.fromRGBO(134, 131, 145, 1),
                          fontSize: 14.0.sp,
                          fontWeight: FontWeight.w400)),
                ],
              ),
            ),
          ),
        Container(
          height: 70.w,
          padding: EdgeInsets.only(right: 30),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Padding(
                padding: EdgeInsets.only(right: 10),
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(46), // 设置圆角半径
                  child: PublicImage(
                    image: widget.DApp.logo ?? '',
                    width: 46.w,
                    height: 46.w,
                  ),
                ),
              ),
              Expanded(
                  child: Column(
                mainAxisSize: MainAxisSize.max,
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Padding(
                    padding: EdgeInsets.only(bottom: 3),
                    child: Text(
                      widget.DApp.name!,
                      overflow: TextOverflow.ellipsis,
                      maxLines: 1,
                      style: TextStyle(
                        fontSize: 16.sp,
                        height: (20 / 16).w,
                        fontWeight: FontWeight.w500,
                        color: Color.fromRGBO(51, 51, 51, 1),
                      ),
                    ),
                  ),
                  Text(widget.DApp.url!,
                      overflow: TextOverflow.ellipsis,
                      maxLines: 1,
                      style: TextStyle(
                        fontSize: 12.sp,
                        height: (17 / 12).w,
                        fontWeight: FontWeight.w400,
                        color: Color.fromRGBO(190, 189, 202, 1),
                      ))
                ],
              ))
            ],
          ),
        ),
        if (!isFavorite)
          Container(
            width: 335.w,
            padding: EdgeInsets.fromLTRB(15, 12, 15, 12),
            margin: EdgeInsets.only(top: 10),
            decoration: BoxDecoration(
              color: Color.fromRGBO(255, 248, 241, 1),
              borderRadius: BorderRadius.circular(10),
            ),
            child: Row(
              mainAxisSize: MainAxisSize.max,
              children: [
                Padding(
                    padding: EdgeInsets.only(right: 10),
                    child: Image.asset(
                      'assets/images/dapp/warn.png',
                      width: 20.w,
                      height: 20.w,
                    )),
                Expanded(
                    flex: 1,
                    child: Text(
                      'We cannot guarantee the security of this dapp Please be careful when adding favorites!!!',
                      softWrap: true,
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                        fontSize: 12.sp,
                        height: (16 / 12).w,
                        fontWeight: FontWeight.w400,
                        color: Color.fromRGBO(255, 81, 0, 1),
                      ),
                    ))
              ],
            ),
          ),
        Container(
          width: 335.w,
          margin: EdgeInsets.only(top: 30),
          child: GestureDetector(
            onTap: () {
              print('GestureDetector-${isCheck}');
              setState(() {
                isCheck = !isCheck;
              });
            },
            child: Row(
              mainAxisSize: MainAxisSize.max,
              children: [
                Container(
                  padding: EdgeInsets.zero,
                  width: 18.w,
                  height: 18.w,
                  child: Checkbox(
                      value: isCheck,
                      materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                      activeColor: '#8667FE'.toColor(),
                      side: BorderSide(color: '#BEBDCA'.toColor()),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(4), // 设置圆角半径
                      ),
                      onChanged: (value) {
                        print('onChanged-${value}');
                        setState(() {
                          isCheck = !isCheck;
                        });
                      }),
                ),
                SizedBox(
                  width: 6.w,
                ),
                Expanded(
                    flex: 1,
                    child: Text(
                      "I already know,Don't remind again",
                      softWrap: true,
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                        fontSize: 12.sp,
                        height: (17 / 12).w,
                        fontWeight: FontWeight.w400,
                        color: Color.fromRGBO(134, 131, 145, 1),
                      ),
                    ))
              ],
            ),
          ),
        ),
        Container(
          margin: EdgeInsets.only(top: 20),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10),
          ),
          child: HoverStatus(
            defaultColor: Color.fromRGBO(134, 103, 254, 1),
            hoverColor: Color.fromRGBO(109, 77, 231, 1),
            radius: 10,
            child: Container(
              width: 335.w,
              height: 55.w,
              alignment: Alignment.center,
              child: Text(
                'Confirm',
                style: TextStyle(
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w500,
                  color: Color.fromRGBO(255, 255, 255, 1),
                ),
              ),
            ),
            onPressed: () {
              if (isFavorite) {
                Provider.of<DAppProvider>(context, listen: false)
                    .removeFavorite(widget.DApp);
                if (isCheck) {
                  List<String> list = SP().getCancelStatusList();
                  list.add(widget.DApp.uid!);
                  SP().setCancelStatusList(list);
                }
              } else {
                Provider.of<DAppProvider>(context, listen: false)
                    .addFavorite(widget.DApp);
                if (isCheck) {
                  List<String> list = SP().getFavoriteStatusList();
                  list.add(widget.DApp.uid!);
                  SP().setFavoriteStatusList(list);
                }
                if (widget.needToast!) {
                  Toast.show(context,
                      message: 'Favorites succeeded',
                      duration: Duration(milliseconds: 2000));
                }
              }
              widget.onConfirm?.call();
              Navigator.pop(context);
            },
          ),
        )
      ]),
    ));
  }
}
